package cputils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import thread.WYServiceThread;

import common.Utils;

public class CPHMWYService {
	
//	private static DateFormat format = new SimpleDateFormat("MM-dd HH:mm:ss");

	public static void main(String[] args) throws IOException {
		CPHMWYService service = new CPHMWYService();
		//writeAicaiDLTHMData("14026");
	//	writeAicaiSSQHMData("2014025");
//		service.writeTaobaoHMData("SSQ","2014028",false);
//		writeTaobaoHMData("SSQ","2014027",false);
//		writeTaobaoHMData("SSQ","2014026",false);
		for (int i = 2014031; i <= 2014031; i++) {
			//new Wy("ssq", "2014031", true);
		}
		new WYServiceThread("ssq", "2014031", true).run();
//		List<?> notfulldetailLinks = service.readDetailLink163("dlt", "14032", 2, true);
//		System.out.println("not full:"+notfulldetailLinks.size());
//		List<?> fulldetailLinks = service.readDetailLink163("dlt", "14032", 3, true);
//		System.out.println("full:"+fulldetailLinks.size());
//		service.writeWYHMData("dlt", "14032", true);
//		service.tjHM4WY("14032");
//		service.readDataHMWY("2014032121CP24446879");
	}
	public Map<String, Map<Integer, Integer>> tjHM4WY(String issueNo) throws IOException{
		Map<String, Map<Integer, Integer>> fullMap = tjHM4Taobao("wy_"+issueNo+"_full",2);
		System.out.println(fullMap);
		Map<String, Map<Integer, Integer>> notfullMap = tjHM4Taobao("wy_"+issueNo+"_notfull",1);
		System.out.println(notfullMap);
		
		Map<String, Map<Integer, Integer>> map = tjHM4Taobao("wy_"+issueNo+"_",100);
		System.out.println(map);
		return map;
	}
	private Map<String, Map<Integer, Integer>> tjHM4Taobao(String fileName,int is_not_full) throws IOException{
		Map<String, Map<Integer, Integer>> res = new HashMap<String, Map<Integer,Integer>>();
		List<String> list = new ArrayList<String>();
		if (is_not_full == 100) {
			list = XmlUtils.getHMData(fileName+"notfull");
			list.addAll(XmlUtils.getHMData(fileName+"full"));
			fileName = fileName+"all";
		}else {
			list = XmlUtils.getHMData(fileName);
		}
		Map<Integer, Integer> bMap = new HashMap<Integer, Integer>();
		Map<Integer, Integer> aMap = new HashMap<Integer, Integer>();
		for (int i = 1; i <= 35; i++) {
			bMap.put(i, 0);
		}
		for (int i = 1; i <= 16; i++) {
			aMap.put(i, 0);
		}
		for (String s : list) {
			//s = XmlUtils.replaceHanzi(s, ",");
			//s = s.replaceAll(" ", "");
			s = s.replaceAll("\\(", " ").replaceAll("\\)", " ");
			String[] sArr = s.split("\\:");
			if (sArr!=null&&sArr.length==2) {
				String[] bArr = sArr[0].split(" ");
				String[] aArr = sArr[1].split(" ");
				for (int i = 0; i < bArr.length; i++) {
					if (StringUtils.isNotBlank(bArr[i])) {
						int num = Integer.parseInt(bArr[i].trim());
						if (bMap.get(num)!=null) {
							bMap.put(num, bMap.get(num)+1);
						}
					}
				}
				for (int i = 0; i < aArr.length; i++) {
					if (StringUtils.isNotBlank(aArr[i])) {
						int num = Integer.parseInt(aArr[i].trim());
						if (aMap.get(num)!=null) {
							aMap.put(num, aMap.get(num)+1);
						}
					}
				}
			}
		}
		res.put("b", bMap);
		res.put("a", aMap);
		Utils.print(fileName+" line:"+list.size());
		res = XmlUtils.makeMap(res, true);
		return res;
	}
	
	public void writeWYHMData(String game,String issueNo,boolean onsale){
		writeWYHMData(game, issueNo, 3,onsale);//full
		writeWYHMData(game, issueNo, 2,onsale);//not full
	}
	
	public void writeWYHMData(String game,String issueNo,int is_not_full,boolean onsale){
		String fullOrNotStr = getFullOrNotName(is_not_full);
		Utils.print("****WY "+game+" "+issueNo+"("+fullOrNotStr+") HMDetailLinks begin...");
		long b1 = System.currentTimeMillis();
		List<String> lottOrderIds = readDetailLink163(game, issueNo, is_not_full, onsale);
		Utils.print("****WY "+game+" "+issueNo+"("+fullOrNotStr+") HMDetailLinks ok..."+lottOrderIds.size()+"...time:"+(System.currentTimeMillis()-b1)+"ms");
		int size = lottOrderIds.size();
		List<String> dataList = new ArrayList<String>();
		int i = 1;
		int totalRec = 0;
		Utils.print("****WY "+game+" "+issueNo+"("+fullOrNotStr+") HMData begin...");
		long b2 = System.currentTimeMillis();
		for (String li : lottOrderIds) {
			List<String> datas = readDataHMWY(li);
			if(i%500==0){
				Utils.print("********WY "+game+" "+issueNo+"("+fullOrNotStr+") HMData..."+(i)+"("+li+"--"+datas.size()+")->"+size);
			}
			dataList.addAll(datas);
			i++;
		}
		Utils.print("****WY "+game+" "+issueNo+"("+fullOrNotStr+") HMData ok..."+dataList.size()+".time:"+(System.currentTimeMillis()-b2));
		Utils.print("****WY "+game+" "+issueNo+"("+fullOrNotStr+") HMData write begin...");
		long b3 = System.currentTimeMillis();
		StringBuilder cBuilder = new StringBuilder();
		for (String data : dataList) {
			totalRec++;
			//data = data.replaceAll(" ", "").replaceAll(" ", "");
			cBuilder.append(data).append("\r\n");
		}
		Utils.print("****WY "+game+" "+issueNo+"("+fullOrNotStr+") HMData write ok..."+dataList.size()+".time:"+(System.currentTimeMillis()-b3));
		XmlUtils.writeFile(cBuilder.toString(), "wy_"+issueNo+"_"+fullOrNotStr+".txt", false);
		Utils.print("WY issueNo: "+issueNo+"("+fullOrNotStr+") finished...users:"+lottOrderIds.size()+" records:"+totalRec);
	}
	
	
	public Map<String,Object> lastIssuoInfo(String game){
		String url = "http://caipiao.taobao.com//lottery/ajax/get_united_list.htm" +
				"?page="+dataLinkPageNo+"&issue=&lotteryType="+game+"&playType=&commission_rate=-1"+
				"&confidential=1&united_fee=0-0&is_not_full=1&creator=&sort_obj=bonusRatio&sort=desc&change_sort=false"+
				"&lowAmount=0&highAmount=0&from=&onsale=&t="+System.currentTimeMillis();
		Connection conn = Jsoup.connect(url);
		Document doc = null;
		int i = 1;
		while (doc == null) {
			try {
				doc = conn.get();
			} catch (IOException e) {
				//e.printStackTrace();
				++i;
				if (i>10) {
					Utils.print("********("+e.getMessage()+")Try to read 10("+i+") times.");
//					System.exit(0);
				}
				conn = Jsoup.connect(url);
			}
		}
		String resultStr = doc.text();
		Map<String,Object> infoMap = new HashMap<String, Object>();
		JSONObject object = JSONObject.fromObject("{\""+resultStr.substring(resultStr.indexOf("totalItem")));
		infoMap.put("totalItem", object.get("totalItem"));
		infoMap.put("lotteryType", object.get("lotteryType"));
		infoMap.put("totalPage", object.get("totalPage"));
		List<String> issueList = new ArrayList<String>();
		JSONArray arr = object.getJSONArray("issueList");
		for (Object object2 : arr) {
			JSONObject object3 = (JSONObject) object2;
			issueList.add(object3.getString("issue"));
			if (object3.getBoolean("onsale")) {
				infoMap.put("onsaleIssueNo", object3.get("issue"));
			}
		}
		infoMap.put("issueList", issueList);
		return infoMap;
	}
	private int dataLinkPageNo = 1;
	/**
	 * @param game
	 * @param issueNo
	 * @param is_not_full
	 * @return detailLink 详情界面链接
	 */
	private  List<String> readDetailLink163(String game,String issueNo,int is_not_full,boolean onsale){
		String fullOrNotStr = getFullOrNotName(is_not_full);
		/*<input type="hidden" id="currentGroupbuyPeriod" value="14032" />
		parameter.status "2" 未满员     "3"已满员     "4"已撤单
		parameter.proportion 
		"-1" 不限佣金    "0"  = 0  "0.01" <= 1
		("0.02" <= 2)("0.03" <= 3)("0.04" <= 4)("0.05" <= 5)
		("0.06" <= 6)("0.07" <= 7)("0.08" <= 8)("0.09" <= 9)

		guarantee ("0"  不限保底)("0.05"  >= 5)("0.1" >= 10)("0.15" >= 15)
		("0.2" >= 20)("0.25" >= 25)("0.3" >= 30)
		orderBy=bonus(奖金排序)
		*/
		String url = "http://caipiao.163.com/groupbuy/" +game+
				"/?pageNum="+dataLinkPageNo+"&sortType=desc&orderBy=remain_pieces" +
				"&parameter.status="+is_not_full+"&showTop=not&difdisplay=false"+
				"&parameter.proportion=-1&parameter.createrNickName="+
				"&parameter.period="+issueNo;
		Connection conn = Jsoup.connect(url);
		Document doc = null;
		int i = 1;
		while (doc == null) {
			try {
				doc = conn.get();
			} catch (IOException e) {
				//e.printStackTrace();
				++i;
				if (i>10) {
					Utils.print("********("+e.getMessage()+")Try to read 10("+i+") times.");
//					System.exit(0);
				}
				conn = Jsoup.connect(url);
			}
		}
		
		int totalPage = Integer.parseInt(doc.getElementsByClass("jumptoTxt").get(0).attr("maxPage"));
		List<String> resList = new ArrayList<String>();
		Element tableE = doc.getElementsByClass("group_buy").get(0);
		Elements trs = tableE.getElementsByTag("tr");
		for (int m = 1,len=trs.size();m<len;m++) {
			Element element = trs.get(m);
			if ("public".equals(element.child(0).child(1).attr("class"))) {
				//resList.add("http://caipiao.163.com"+element.child(8).child(1).attr("href"));
				resList.add(element.child(8).child(0).attr("lotoorder"));
			}
		}
		/*Elements hrefs = doc.getElementsByTag("a");
		for (Element element : hrefs) {
			if ("btn_mini".equals(element.attr("class"))) {
				resList.add("http://caipiao.163.com"+element.attr("href"));
			}
		}*/
		if (dataLinkPageNo%10==0) {
			Utils.print("********WY "+game+" "+issueNo+"("+fullOrNotStr+") HMDetailLinks pageNo:"+dataLinkPageNo+" totalPage:"+totalPage);
		}
		dataLinkPageNo++;
		if (totalPage>1&&totalPage>=dataLinkPageNo) {
			resList.addAll(readDetailLink163(game, issueNo, is_not_full,onsale));
		}else {
			dataLinkPageNo = 1;
		}
		return resList;
	}
	
	
	

	private int hmdatapageNo = 1;
	private List<String> readDataHMWY(String lottOrderId){
		//http://caipiao.163.com/hit/gd_shuzi_detail.html?pageNum=1&pageSize=10&
			//lottOrderId=2014031922CP05952095&stamp=1395403769673
		String url = "http://caipiao.163.com/hit/gd_shuzi_detail.html?pageSize=10&pageNum="+hmdatapageNo
				+"&lottOrderId="+lottOrderId+"&stamp="+System.currentTimeMillis();
		Connection conn = Jsoup.connect(url);
		Document doc = null;
		int i = 1;
		while (doc == null) {
			try {
				doc = conn.get();
			} catch (IOException e) {
				++i;
				if (i>10) {
					Utils.print("********("+e.getMessage()+")Try to read 10("+i+") times.");
//					System.exit(0);
				}
				conn = Jsoup.connect(url);
			}
		}
//		System.out.println("----------"+lottOrderId+"---"+hmdatapageNo);
		List<String> resList = new ArrayList<String>();
		if (doc.getElementById("fcase_page_num")!=null) {
			int totalItems = Integer.parseInt(doc.getElementById("fcase_page_num").attr("value"));
			int pages = (totalItems/10)+(totalItems%10==0?0:1);
			
			
			Element tableE = doc.getElementsByClass("table_szc").get(0);
			Elements trs = tableE.getElementsByTag("tr");
			for (int m = 1,len=trs.size();m<len;m++) {
				Element element = trs.get(m);
				//resList.add(element.child(1).child(1).text()+":"+element.child(1).child(4).text());
				String b = "";
				Elements spansb = element.child(1).getElementsByClass("c_ba2636");
				if (spansb.size()==1) {
					if (element.child(1).child(1).text().indexOf("...")==-1) {
						b = element.child(1).child(1).text();
					}else {
						b = element.child(1).child(1).attr("inf");
					}
				}else {
					for (int j = 0,size=spansb.size();j<size; j++) {
						Element element2 = spansb.get(j);
						//System.out.println(element2.nextElementSibling().text());
						Element next = element2.nextElementSibling();
						if (next.text().indexOf("...")==-1) {
							if (j==0) {
								b+="("+next.text()+")";
							}else {
								b+=next.text();
							}
						}else {
							if (j==0) {
								b+="("+next.attr("inf")+")";
							}else {
								b+=next.attr("inf");
							}
						}
					}
				}
				
				String a = "";
				Elements spansa = element.child(1).getElementsByClass("c_1e50a2");
				if (spansa.size()==1) {
					if (element.child(1).child(4).text().indexOf("...")==-1) {
						a = element.child(1).child(4).text();
					}else {
						a = element.child(1).child(4).attr("inf");
					}
				}else {
					for (int j = 0,size=spansa.size();j<size; j++) {
						Element element2 = spansa.get(j);
						Element next = element2.nextElementSibling();
						if (next.text().indexOf("...")==-1) {
							if (j==0) {
								a+="("+next.text()+")";
							}else {
								a+=next.text();
							}
						}else {
							if (j==0) {
								a+="("+next.attr("inf")+")";
							}else {
								a+=next.attr("inf");
							}
						}
					}
					//System.out.println("-----------------------------------------------------------"+lottOrderId);
					//System.out.println("-----------------------------------------------------------"+b+":"+a);
				}
				resList.add(b+":"+a);
				//System.out.println(b+":"+a);
			}
			if (pages>1) {
				hmdatapageNo++;
				if (pages>=hmdatapageNo) {
					resList.addAll(readDataHMWY(lottOrderId));
				}else {
					hmdatapageNo = 1;
				}
			}
		}
		
		return resList;
	}
	
	private String getFullOrNotName(int is_not_full){
		String fullOrNotStr = "";
		switch (is_not_full) {
		case 2:
			fullOrNotStr = "notfull";
			break;
		case 3:
			fullOrNotStr = "full";
			break;
		default:
			break;
		}
		return fullOrNotStr;
	}
	
}
/*public class WYServiceThread implements Runnable{
	private String game;
	private String issueNo;
	private boolean onsale;
	public WYServiceThread(String game,String issueNo,boolean onsale){
		this.game = game;
		this.issueNo = issueNo;
		this.onsale = onsale;
	}
	
	@Override
	public void run() {
		CPHMWYService service = new CPHMWYService();
		service.writeWYHMData(game, issueNo, onsale);
	}
	
}*/